package com.wlf.aiinterview.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlf.aiinterview.annotation.CheckAuth;
import com.wlf.aiinterview.common.BaseResponse;
import com.wlf.aiinterview.common.ErrorCode;
import com.wlf.aiinterview.common.ResultUtils;
import com.wlf.aiinterview.constant.UserConstant;
import com.wlf.aiinterview.exception.BusinessException;
import com.wlf.aiinterview.model.dto.user.*;
import com.wlf.aiinterview.model.pojo.User;
import com.wlf.aiinterview.model.vo.UserVO;
import com.wlf.aiinterview.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    //添加用户 注册
    @PostMapping("/add")
    public BaseResponse<Integer> userRegister(@RequestBody UserAddDto userDto) {
        if (userDto == null) {
            log.info("参数为{}", userDto);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数为空");
        }
        String useraccount = userDto.getUseraccount();
        String userpassword = userDto.getUserpassword();
        String checkpassword = userDto.getCheckpassword();
        Integer i = userService.addUser(useraccount, userpassword, checkpassword);
        //0 代表成功 -1 代表失败
        return ResultUtils.success(i);
    }

    @PostMapping("/login")
    public BaseResponse<Integer> login(@RequestBody UserLoginDto userLoginDto, HttpServletRequest request) {
        if (userLoginDto == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请求参数为null");
        }
        String userAccount = userLoginDto.getUserAccount();
        String password = userLoginDto.getPassword();
        List<User> users = userService.userLogin(userAccount, password, request);
        if (users.size() == 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户不存在");
        }
        return ResultUtils.success(UserConstant.SUCCESS);
    }

    @DeleteMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request) {
        Boolean b = userService.userLogout(request);
        if (!b) {
            ResultUtils.error(ErrorCode.OPERATION_ERROR, "未登录");
        }
        return ResultUtils.success(b);
    }

    /**
     * 获取当前登录
     */
    @GetMapping("/getlogin")
    public BaseResponse<User> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        return ResultUtils.success(loginUser);
    }

    /**
     * 添加用户
     *
     * @param userAddDto
     * @return
     */
    @CheckAuth(role = UserConstant.ADMIN)
    @PostMapping("/admin/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddDto userAddDto) {
//判断参数
        if (userAddDto == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数为空");
        }
        //插入数据库
        User user = new User();
        BeanUtils.copyProperties(userAddDto, user);
        String s = DigestUtils.md5DigestAsHex((UserConstant.DEAFAULTPASS + UserConstant.SALT).getBytes());
        user.setUserpassword(s);
        boolean save = userService.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "插入失败");
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param request
     * @return
     */
    @CheckAuth(role = UserConstant.ADMIN)
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteUser(DeleteRequest request) {
        //判断参数
        if (request == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数为空");
        }
        //删除
        Long id = request.getId();
        boolean b = userService.removeById(id);
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
        }
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param request
     * @return
     */
    @CheckAuth(role = UserConstant.ADMIN)
    @PutMapping("/update")
    public BaseResponse<Boolean> uodateUser(UserUpdateRequest request) {
        //判断参数
        if (request == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数为空");
        }
        //更新
        User user = new User();
        BeanUtils.copyProperties(request, user);
        boolean b = userService.updateById(user);
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }
        return ResultUtils.success(b);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @CheckAuth(role = UserConstant.ADMIN)
    @GetMapping("/get")
    public BaseResponse<User> getUserByid(long id) {
        if (id < 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数错误");
        }
        User user = userService.getUserById(id);
        return ResultUtils.success(user);
    }

    /**
     * 根据id查询用户包装类
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVoByid(long id) {
        BaseResponse<User> response = getUserByid(id);
        User user = response.getData();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 分页查询
     *
     * @param pageDto
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<User>> listUserByPage(@RequestBody PageDto pageDto) {
        //校验参数
        if (pageDto == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "参数错误");
        }
        //调用方法
        int pageSize = pageDto.getPageSize();
        int current = pageDto.getCurrent();
        String sortField = pageDto.getSortField();
        Page<User> userPage = userService.listBypageQuery(current, pageSize, sortField);
        if (userPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取分页查询失败");
        }
        return ResultUtils.success(userPage);
    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVoByPage(@RequestBody PageDto pageDto) {
        BaseResponse<Page<User>> pageBaseResponse = listUserByPage(pageDto);
        Page<User> data = pageBaseResponse.getData();
        List<User> records = data.getRecords();
        List<UserVO> collect = records.stream().map(s -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(s, userVO);
            return userVO;
        }).collect(Collectors.toList());
        int pageSize = pageDto.getPageSize();
        int current = pageDto.getCurrent();
        Page<UserVO> userVOPage = new Page<>(current, pageSize);
        userVOPage.setRecords(collect);
        return ResultUtils.success(userVOPage);
    }
}
